#!/usr/bin/env python
# -*- coding:utf8 -*-
#http://lexus.cnblogs.com
#frederick.mao@gmail.com
#python utilities
#write @20090901

def save2file(content,filename):
    """
    将内容保存到文本中
    """
    fp = open ( filename, "w" )
    fp.write(content)
    fp.close
    
def exeTime(func):
    """
    装饰器函数，以aop的方式记录函数执行时间
    """
    def newFunc(*args, **args2):
        import time  
        t0 = time.time()  
        print "@%s, {%s} start" % (time.strftime("%X", time.localtime()), func.__name__)  
        back = func(*args, **args2)  
        print "@%s, {%s} end" % (time.strftime("%X", time.localtime()), func.__name__)  
        print "@%.3fs taken for {%s}" % (time.time() - t0, func.__name__)  
        return back  
    return newFunc  

@exeTime
def save(obj,filename_with_fullpath):
    "对对象进行序列化操作"
    import cPickle;
    f=file(filename_with_fullpath,'wb')
    cPickle.dump(obj,f,2)
    f.close()
    
@exeTime
def load(filename_with_fullpath):
    "反序列化并返回对象"
    import cPickle;
    f=file(filename_with_fullpath,'rb')
    result=cPickle.load(f)
    f.close()
    return result


def getcwd():
    """
    获取脚本当前的路径
    """
    import sys
    import os
    pwd = sys.path[0]
    if os.path.isfile(pwd):
        pwd = os.path.dirname(pwd)
    return pwd

def getcurrentdatetime():
    """
    获取当前的年月日小时分秒
    """
    import time
    return time.strftime("%Y%m%d_%H%M%S",time.localtime())

def createfolders(fullpath):
    import os
    print fullpath
    if os.path.exists(fullpath)<>True:
        os.makedirs(fullpath)

def getencoding(fullpath):
    import codecs
    #detect the file encoding
    real_encoding = None
    encodings = ('utf-16', 'utf-8', 'gb2312')
    for encoding in encodings:
        logfile = codecs.open(fullpath, 'r', encoding=encoding)
        try:
            logfile.readline()
        except UnicodeError:
            logfile.close()
        else:
            real_encoding = encoding
            logfile.close()
            break
    if not real_encoding:
        logging.error("what's the file encoding? i cannot figure out :(")
        return
    logfile = codecs.open(fullpath, 'r', encoding=real_encoding)
    return real_encoding

def get_specific_file_list(directory,predication=None):
    import os
    list=[]
    for parent, dirnames, filenames in os.walk(directory):
        for filename in filenames:
            fullpath=os.path.join(parent, filename)
            if predication is None:
                list.append(fullpath)
            if(predication is not None) and predication(filename):
                list.append(fullpath)
    return list

def combine_files(list,onefile):
    """
        list将待合并的文件路径集合传入进去
        onefile新合并完后的文件路径
    """
    import codecs
    new = codecs.open(onefile, 'a',encoding='utf-16')
    for o in list:
        f=codecs.open(o,'r',encoding='utf-16')
        new.write(f.read())
        f.close()
    new.close()

    